﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ComTools.File
{
    using System;
    using System.IO;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;

    /// <summary>
    /// XML操作帮助类
    /// </summary>
    public class XmlOperateHelper
    {
        /// <summary>
        /// 将XML文件反序列化为对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="fileName">文件路径</param>
        /// <returns>反序列化的对象</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        public static T DeserilizeFromXmlFile<T>(string fileName) where T : class
        {
            if (string.IsNullOrWhiteSpace(fileName)) throw new ArgumentNullException("fileName", "传入的路径是空字符串或者为null");

            T result;
            try
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    result = (T)serializer.Deserialize(fs);
                }
            }
            catch
            {
                throw;
            }
            return result;
        }

        /// <summary>
        /// 将XML<see cref="string"/>反序列化为对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="xml">XML文本</param>
        /// <returns>反序列化的对象</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        public static T DeserilizeFromXml<T>(string xml) where T : class
        {
            if (string.IsNullOrWhiteSpace(xml)) throw new ArgumentNullException("xml", "传入的xml字符串为空字符串或者为null");
            T result;
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer ser = new XmlSerializer(typeof(T));

                    result = (T)ser.Deserialize(sr);
                }
            }
            catch
            {
                throw;
            }
            return result;
        }

        /// <summary>
        /// 对象生成XML格式<see cref="string"/>
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="t">对象实例</param>
        /// <returns>XML格式的<see cref="string"/></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        public static string XmlToString<T>(T t) where T : class
        {
            if (null == t) throw new ArgumentNullException("t", "传入的对象为null");
            StringBuilder sResult = new StringBuilder();
            try
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.NewLineOnAttributes = true;
                settings.Encoding = Encoding.UTF8;
                settings.OmitXmlDeclaration = true;
                using (XmlWriter writer = XmlWriter.Create(sResult, settings))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                    ns.Add("", "");
                    serializer.Serialize(writer, t, ns);
                }
            }
            catch
            {
                throw;
            }
            return sResult.ToString();
        }

        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        public static void InsertNode(XmlElement element, string path, string parentNodeName)
        {
            if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path", "传入的路径是空字符串或者为null");
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode parent = doc.SelectSingleNode(parentNodeName);
                parent.AppendChild(element);
                doc.Save(path);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 将对象序列化为XML文件
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="fileName">文件路径</param>
        /// <param name="data"></param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        public static void SerializeToXml<T>(string fileName, T data) where T : class
        {
            try
            {
                if (string.IsNullOrWhiteSpace(fileName)) throw new ArgumentNullException("fileName", "传入的文件路径为空字符串或为null");

                using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    serializer.Serialize(fs, data);
                }
            }
            catch
            {
                throw;
            }
        }

    }
}
